package myJs.cps

import cats.effect.SyncIO
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.myPkg.jquery._
import myJs.myPkg.reactBootstrap._
import myJs.myPkg.reactHookForm.{ReactHookForm, UseFormStateOptions}
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.myPkg.Hooks._

import scala.scalajs.js

/** Created by yz on 3/11/2020
  */
object BetweenInlineCp {

  case class Props(
      start: String = "",
      end: String = "",
      label: String,
      startName: String,
      endName: String,
      show: Boolean = true,
      formJq: JQuery = $("#form"),
      questionInfo: String = "",
      startChange: String => SyncIO[Unit] = v=>SyncIO{},
      endChange: String => SyncIO[Unit] = v=>SyncIO{},
      startPlaceholder: String = "",
      endPlaceholder: String = ""
  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>

    val names=List(props.startName,props.endName)
    val formState = ReactHookForm.useFormState(options =
      UseFormStateOptions(
        name = names
      )
    )

    useEffect(
      SyncIO{
        Tool.popover
        ()
      },
      List()
    )

    val hasErrorCls = if (names.exists(formState.errors.deepDefinedAt(_))) "has-error" else ""

    div(
      className := s"form-group ${hasErrorCls}",
      label(
        className := "control-label col-sm-4",
        s"${props.label}",
        if (props.questionInfo.nonBlank) {
          {
            val popover = Popover(id = "popover-basic")(
              Popover.Header("说明"),
              Popover.Body(
                props.questionInfo
              )
            ).rawElement
            OverlayTrigger(
              placement = "auto",
              trigger = js.Array("hover", "focus"),
              overlay = popover
            )(
              span(
                a(`type` := "button", i(className := "fa fa-question-circle-o"))
              )
            )
          }
        } else EmptyVdom,
        ":"
      ),
      div(
        className := "col-sm-8",
        div(
          div(
            className := "col-sm-5",
            paddingLeft := 0.px, paddingRight := 0.px,
            PureInputCp.Props(
              value = props.start,
              name = props.startName,
              onChange = props.startChange,
              placeHolder = props.startPlaceholder
            ).render
          ),
          div(lineHeight := "34px", className := "col-sm-2", "-"),
          div(
            className := "col-sm-5",
            paddingLeft := 0.px, paddingRight := 0.px,
            PureInputCp.Props(
              value = props.end,
              name = props.endName,
              onChange = props.endChange,
              placeHolder = props.endPlaceholder
            ).render
          )
        )
      )
    )

  }

}
